package com.hsyt.pms.org.dubbo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hsyt.pfc.support.rpc.PageResult;
import com.hsyt.pfc.support.util.LoggerUtil;
import com.hsyt.pms.api.dto.org.OrgDto;
import com.hsyt.pms.api.dto.org.OrgTypeQueryDto;
import com.hsyt.pms.api.entity.org.Org;
import com.hsyt.pms.api.vo.org.GridData;
import com.hsyt.pms.api.vo.org.OrgHelp;
import com.hsyt.pms.api.vo.org.OrgTypeVo;
import com.hsyt.pms.api.vo.org.OrgVo;
import com.hsyt.pms.org.dubbo.OrgService;
import com.hsyt.pms.orm.org.OrgDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: OrgTypeServiceImpl
 * @Description: 组织管理实现
 * @author wangze@hsyuntai.com
 * @date 2019年2月12日 下午2:45:51
 */
@Slf4j
@Component
@Service(version = "0.0.1", interfaceClass = OrgService.class, registry = "pms", group = "pmsOrg", timeout = 3000)
public class OrgServiceImpl implements OrgService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrgServiceImpl.class);

    @Resource
    private OrgDao orgDao;

    @Resource
    private OrgGridSearcher orgGridSearcher;

    private static TransportClient client;

    public static String clusterName = "yt-spring-boot-index";

    public static String hostList = "localhost:9300";

    private static Object lock = new Object();

    public int updateByPrimaryKey(OrgDto orgDto) {
        return this.orgDao.updateByPrimaryKey(orgDto);
    }

    @Override
    public int insertOrg(OrgDto orgDto) {
        return orgDao.insertOrg(orgDto);
    }

    @Override
    public String nextSysOrgCode(Long parentOrgId, Integer orgType) {
        String maxSysOrgCode = orgDao.maxSysOrgCode(parentOrgId, orgType);
        return OrgHelp.nextSysOrgCode(maxSysOrgCode);
    }

    @Override
    public GridData pageFindOrgrid(OrgDto orgDto) {
        Page<?> page = PageHelper.startPage(orgDto.getPageNo(), orgDto.getPageSize(), true);
        List<OrgVo> list = this.orgDao.queryOrgByDto(orgDto);
        GridData gridData = new GridData(page.getPageNum(), page.getPages(), (int) page.getTotal());
        gridData.getRows().addAll(list);
        return gridData;
    }

    @Override
    public PageResult<OrgTypeVo> searchPageDataByDto(OrgTypeQueryDto dto) {
        Page<?> page = PageHelper.startPage(dto.getPageNumber(),dto.getPageSize(), true);
        List<OrgTypeVo> list = orgDao.queryOrgTypeByDto(dto);
        PageResult<OrgTypeVo> pageResult =  PageResult.create(page.getTotal(), list);
        return pageResult;
    }


    //-------------------以下通过ElasticSearch检索查询--------------

    @Override
    public Integer createOrgEs() {
        TransportClient esClient = getClient();
        Integer index = null;
        try {
            esClient.admin().indices().prepareDelete("org").execute().actionGet();
            index = orgGridSearcher.createOrgIndex(esClient); // 1: 新增按经纬度排序
//            Settings settings = Settings.builder().put("index.number_of_shards", 5).put("index.number_of_replicas", 1).build();
//            index = orgGridSearcher.createOrgIndex(esClient, settings); // 2: 第一版普通排序
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "【ElasticSearchServiceImpl-createIndex】, 创建索引异常 e.getMessage() : {0}", e.getMessage());
        }
        return index;
    }

    @Override
    public Integer updateOrgEs(Org org) {
        return null;
    }

    @Override
    public Integer deleteOrgEs(Org org) {
        return null;
    }

    @Override
    public PageResult<OrgVo> selectOrgEs(Org org) {
        return null;
    }

    /**
     * 获取服务
     *
     * @return
     */
    public static TransportClient getClient() {
        try {
            if (client == null) {
                synchronized (lock) {
                    String[] hostAndPorts = hostList.split(",");
                    Settings settings = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", true).build();
                    Map<String, Integer> hostInfos = parseHostAndPorts(hostAndPorts);
                    client = new PreBuiltTransportClient(settings);
                    for (Map.Entry<String, Integer> entry : hostInfos.entrySet()) {
                        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(entry.getKey()), entry.getValue()));
                    }
                }
            }
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "构建服务失败：{0}", e.getMessage());
        }
        return client;
    }

    /**
     * 解析端口信息
     *
     * @param hostAndPorts
     * @return
     */
    public static Map<String, Integer> parseHostAndPorts(String[] hostAndPorts) {
        Map<String, Integer> hostMap = new HashMap<String, Integer>();
        if (hostAndPorts == null) {
            return hostMap;
        }
        for (String hostAndPortStr : hostAndPorts) {
            String[] hostAndPort = hostAndPortStr.split(":");
            if (hostAndPort.length != 2 || !StringUtils.isNumeric(hostAndPort[1])) {
                throw new IllegalStateException("端口号信息不正确");
            }
            hostMap.put(hostAndPort[0], Integer.parseInt(hostAndPort[1]));
        }
        return hostMap;
    }

}
